const fs = require('fs');
const path = require('path');
const util = require('util');
const colors = require('colors/safe');
const rootpath = process.argv[2];
let fileObj = {isDirectory: true, content:{}};
let i = 0;

function read(filepath, filename, fileObj) {
    return new Promise(resolve => {
    	// fs.stat(filepath, (err, stats) => {
    	// 	if(err) resolve();
    	// 	else if(!stats.isDirectory()) resolve('Not a directory!');
    	// 	else {

    	// 	}
    	// })
        fs.readdir(filepath, (err, files) => {
            i++;
            if (err) {
                fileObj.isDirectory = false;
                resolve()
            } else {
                Promise.all(files.map(file => {
                    // fileObj.content[file] = {
                    //     isDirectory: true,
                    //     content: {a: 0}
                    // };
                    // console.log(fileObj.content)
                    fileObj.content[file] = {};
                    fileObj.content[file].isDirectory = true;
                    fileObj.content[file].content = {};
                    fileObj.content[file].content.a = 1;
                    return read(path.join(filepath, file), file, fileObj.content[file])
                })).then(() => {
                    resolve();
                    console.log(colors.rainbow(`end: ${files}`))
                });
            }
        })
    })
}
read(rootpath, rootpath, fileObj).then(() => {
	console.dir(util.inspect(fileObj, {depth: null, color: true}))
    console.dir(fileObj.green)
})

function readLoop(filepath, cb) {
	console.log(filepath)
    fs.readdir(filepath, (err, files) => {
    	console.log(filepath)
        if (err) cb(filepath);
        else {
            fileObj[filepath] = files;
            // let j = files.length;
            // function innerLoop(innercb) {
            //     j--;
            //     console.log(j)
            //     const file = files[j];
            //     console.log(`files[j]: ${files[j]}`)
            //     console.log(`file: ${file}`)
            //     readLoop(path.join(filepath, file), (filepath) => {
            //     	console.log(`${filepath} is ended`)
            //         innerLoop(innercb);
            //     })
            //     if(!j) innercb();
            // }

            // innerLoop(() => {
            // 	cb();
            // });
        }
    })
}
// readLoop(rootpath, () => {
// 	console.log(fileObj)
// })